package initialize

import (
	"net/http"
	"strings"
)

type Predicates struct {
	Header HeaderPredicate
	Method string
	Host string
	Path PathPredicate
}

type Filter struct {

}

type Route struct {
	Id string
	Url string
	Predicates Predicates
	Filters []*Filter
}

type Routes []*Route

func(this Routes) Match(request *http.Request) *Route{
	for _,r := range this{
		if this.isMatch(r, request){
			return r
		}
	}
	return nil
}

func (this Routes) isMatch(r *Route,request *http.Request) bool {
	//去掉服务名
	urlFirst := request.URL.Path[1:] //去掉第一个斜杠“/”
	comma := strings.Index(urlFirst, "/") //comma的意思是从字符串urlFirst查找第一个斜杠“/”,然后返回他的位置
	serveName := urlFirst[0:comma]
	servePath := urlFirst[comma:]
	//匹配规则
	if r.Id != serveName{
		return false
	}
	if !r.Predicates.Path.Match(servePath){
		return false
	}
	if !r.Predicates.Header.Match(request.Header){
		return false
	}
	return true
}